package com.example.spi;

import com.example.event.ModuleEvent;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

public class SpiServiceManager implements InitializingBean {
    private Map<String, ModuleService> serviceMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {

        // 使用Java原生ServiceLoader加载所有实现
        ServiceLoader<ModuleService> loader = ServiceLoader.load(ModuleService.class);

        // 注册所有实现到Map中
        for (ModuleService service : loader) {
            serviceMap.put(service.getName(), service);
        }
    }

    // 事件监听器：接收事件并分发给对应的服务
    @EventListener
    public void handleModuleEvent(ModuleEvent event) {
        String moduleName = event.getModuleName();
        ModuleService service = serviceMap.get(moduleName);

        if (service != null && service.supports(event)) {
            service.handleEvent(event);
        }
    }

    /**
     * 根据SPI名称执行对应的服务
     * @param name
     */
    public void executeService(String name) {
        ModuleService service = serviceMap.get(name);
        if (service != null) {
            service.execute();
        } else {
            System.out.println("未找到服务: " + name);
        }
    }

    public Collection<ModuleService> getAllServices() {
        return serviceMap.values();
    }
}